import { Directive, Input } from "@angular/core";
import {
  Validator,
  NG_VALIDATORS,
  ValidatorFn,
  AbstractControl,
  ValidationErrors
} from "@angular/forms";

export const passwordValidator = (
  tip = "entered passwords differ",
  newPasswordName = "newPassword",
  repeatPasswordName = "repeatPassword"
): ValidatorFn => (control: AbstractControl): ValidationErrors => {
  const newPassword = control.get(newPasswordName).value;
  const repeatPassword = control.get(repeatPasswordName).value;
  return newPassword === repeatPassword ? {} : { password: tip };
};

@Directive({
  selector: "[nPassword]",
  providers: [
    { provide: NG_VALIDATORS, useExisting: PasswordValidator, multi: true }
  ]
})
export class PasswordValidator implements Validator {
  @Input() tip = "entered passwords differ";
  @Input() newPasswordName = "newPassword";
  @Input() repeatPasswordName = "repeatPassword";

  validate(control: AbstractControl): ValidationErrors {
    return passwordValidator(
      this.tip,
      this.newPasswordName,
      this.newPasswordName
    )(control);
  }
}
